package com.health.mapp.utils;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;

import com.health.mapp.utils.PropertiesHelper;
import com.health.db.cache.DBCacheFactory;

public class PropertiesHelper {
	
	public final static int SMS_EXPIRE_TIME = 300;
	
	public static String SMS_CACHE_KEY = "SMS:CHECKCODE:%s";
	
	public static String SMS_SERVICE_PASSWORD_CACHE_KEY = "SMS:SERVICE:PASSWORD:CHECKCODE:%s";

	public static String SMS_CHECK_CODE_TEMPLATE = "您本次注册验证码[%s]。超人在守，流量无忧。点击http://www.x.cn/xflow 免费安装【流量超人�?";
	
	public static String SMS_SERVICE_PASSWORD_CODE_TEMPLATE = "您本次找回服务密码的验证码[%s]。超人在守，流量无忧。点击http://www.x.cn/xflow 免费安装【流量超人�?";

	public static String SMS_CHECK_CODE_TEMPLATE_NO_SIGN = "您本次注册验证码[%s]。超人在守，流量无忧。点击http://www.x.cn/xflow 免费安装";

	private static ResourceBundle RESOURCE_BUNDLE = null;

	private static Logger logger = Logger.getLogger(PropertiesHelper.class);

	public PropertiesHelper(String tag) {
		String key = String.format("Bundle:%s", tag);
		RESOURCE_BUNDLE = (ResourceBundle) DBCacheFactory.getInstance().get(key);
		if (null == RESOURCE_BUNDLE ) {
			try {
				String inResourceBundleName = null;
				String OutResourceBundleName = null;
				logger.debug(String.format("create bundle.(%s)", tag));
				// com.ailk.boss.cmcc.henan.utils
				inResourceBundleName = String.format("/resources/config.%s.properties", tag);
				OutResourceBundleName = String.format("resources.config.%s.properties", tag);
				try {
					RESOURCE_BUNDLE = ResourceBundle.getBundle(OutResourceBundleName);
					logger.debug("Get ResourceBundle from " + OutResourceBundleName);
				} catch (MissingResourceException e) {
					RESOURCE_BUNDLE = loadProperties(inResourceBundleName);
					logger.debug("Get ResourceBundle from " + inResourceBundleName);
				}

				DBCacheFactory.getInstance().put(key, RESOURCE_BUNDLE);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
//			logger.debug(String.format("Found bundle in cache.(%s)", tag));
		}
	}

	protected ResourceBundle loadProperties(String bundleName) {
		ResourceBundle rb = null;
		try {
			InputStream in = new BufferedInputStream(this.getClass().getResourceAsStream(bundleName));
			rb = new PropertyResourceBundle(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return rb;
	}

	public String getString(String key) {
		try {
			return RESOURCE_BUNDLE.getString(key);
		} catch (MissingResourceException e) {
			return '!' + key + '!';
		}
	}

	public int getInteger(String key, int defaultInt) {
		try {
			return Integer.valueOf(RESOURCE_BUNDLE.getString(key));
		} catch (MissingResourceException e) {
			return defaultInt;
		}
	}

	public String getProperties(String key) {
		return getString(key);
	}
}
